package fr.labri.harmony.analysis.jsep.results.filter;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import fr.labri.harmony.analysis.jsep.results.Counter;
import fr.labri.harmony.analysis.jsep.results.LoadRules;
import fr.labri.harmony.analysis.jsep.results.Pair;
import fr.labri.harmony.analysis.jsep.results.ProjectActivity;

public class MigrationEvolutionRatio extends ResultFilter {

	@Override
	public void computeResult(ResultSet rs) throws SQLException, IOException {
		rs.first();
		Counter c = new Counter();
		//Number of migration per periods
		Map<Integer,Integer> migration_periods = new HashMap<Integer, Integer>();
		//Number of projects active per periods
		List<Integer> project_periods = ProjectActivity.getProjectPeriod();
		Set<String> libs = new HashSet<String>();
		int nb_migration=0;
		int nb_true_migration=0;
		while (rs.next()){			
			String source = rs.getString("NAME");
			String target = rs.getString("MIGRATION_LIB_TO");
			if(target!=null) {
				libs.add(source);
				libs.add(target);
				nb_migration++;
				int idxCat = LoadRules.getRuleCat(source, target);
				if(idxCat>=0) {
					nb_true_migration++;
					long datemig = Long.parseLong(rs.getString("TIMESTAMP_OUT"))*1000;
					c.incrDateCat(idxCat+1, datemig, false);
					int idxperiod = Utils.getPeriod(datemig);
					if(idxperiod>=0) {
						if(migration_periods.get(idxperiod)==null) migration_periods.put(idxperiod,0);
						migration_periods.put(idxperiod, migration_periods.get(idxperiod)+1);
					}
				}
			}
		}
		PrintStream ps = new PrintStream(new FileOutputStream("Evolution_ratio.csv"));
		int cpt=0;
		ps.println("Start,End,Migration,Project Active,Ratio");
		for(Pair<Long,Long> pair : Utils.dates) {
			int nbmig_period = migration_periods.get(cpt);
			int nbproject_actif = project_periods.get(cpt);
			double ratio = (double)nbmig_period/(double)nbproject_actif;
			ps.println(Utils.formatDate(pair.getElement0())+","+Utils.formatDate(pair.getElement1())+","+nbmig_period+"," + nbproject_actif + ","+Utils.formatDouble(ratio));
			cpt++;
		}
		ps.close();
		c.viewCSVDateCat(new FileOutputStream("migrations_date.csv"));

		ps = new PrintStream(System.out);
		ps.println("Nombre Total de Migrations " + nb_migration);
		ps.println("Nombre Total de Vraies Migrations "+ nb_true_migration);
		ps.println("Nombre Total de Libs dans les migrations "+ libs.size());
	}

}
